package http_middleware

import (
	"github.com/gin-gonic/gin"
	"starry_sky/internal/dal"
	"starry_sky/internal/model"
	"starry_sky/internal/tools/logger"
	"strings"
)

var pathMap = make(map[string]string)

func init() {
	pathMap["home"] = "权限测试页面"

	//驱动管理
	{
		pathMap["driveSave"] = "新增驱动"
		pathMap["driveDelete"] = "删除驱动"
	}
	//模板管理
	{
		pathMap["deviceTemplateSave"] = "保存设备模板"
		pathMap["deviceTemplateDelete"] = "删除设备模板"
	}
	//输入通道管理
	{
		pathMap["inputChannelCreate"] = "新增采集通道"
		pathMap["inputChannelUpdate"] = "更新采集通道"
		pathMap["inputChannelDelete"] = "删除采集通道"
		pathMap["inputChannelEnable"] = "开启采集通道"
		pathMap["inputChannelUnable"] = "停止采集通道"
		pathMap["inputVariableCreate"] = "新增采集变量"
		pathMap["inputVariableUpdate"] = "更新采集变量"
		pathMap["inputVariableDelete"] = "删除采集变量"
	}
	//控制通道管理
	{
		pathMap["controlChannelCreate"] = "新增控制通道"
		pathMap["controlChannelUpdate"] = "更新控制通道"
		pathMap["controlChannelDelete"] = "删除控制通道"
		pathMap["controlChannelEnable"] = "开启控制通道"
		pathMap["controlChannelUnable"] = "停止控制通道"
		pathMap["saveControlVariables"] = "保存控制变量"
		pathMap["removeControlVariable"] = "删除控制变量"
	}
	//输出通道
	{
		pathMap["channelSave"] = "保存输出通道"
		pathMap["channelDelete"] = "删除输出通道"
		pathMap["channelEnable"] = "开启输出通道"
		pathMap["channelUnable"] = "停止输出通道"
		pathMap["variableSave"] = "保存输出变量"
		pathMap["variableDelete"] = "删除输出变量"
		pathMap["functionSave"] = "保存自定以方法"
		pathMap["functionDelete"] = "删除自定义方法"
	}
	//存储管理
	{
		pathMap["storageSave"] = "保存数据库参数"
	}
	//用户管理
	{
		pathMap["user"] = "新增用户"
		pathMap["edit"] = "更新用户"
		pathMap["resetPW"] = "重置用户密码"
		pathMap["del"] = "删除用户"
		pathMap["enable"] = "开启用户"
	}
	//角色管理
	{
		pathMap["role"] = "新增角色"
		pathMap["editRole"] = "更新角色"
		pathMap["delRole"] = "删除角色"
		pathMap["saveRolePermission"] = "保存角色资源"
	}
	//资源管理
	{
		pathMap["permission"] = "新增资源"
		pathMap["editPer"] = "更新资源"
		pathMap["delPer"] = "删除资源"
		pathMap["enablePer"] = "启用/停止资源"
	}
}

// OperationLog 拦截用户操作 记录操作日志
func OperationLog(c *gin.Context) {
	path := c.FullPath() //获取我们本次请求的接口
	pathStrs := strings.Split(path, "/")
	if s, ok := pathMap[pathStrs[len(pathStrs)-1]]; ok {
		u, _ := c.Get("userId")
		err := dal.Insert[model.OperationLog](model.NewOperationLog(u.(string), s))
		if err != nil {
			logger.SysErrorF("OperationLog error: %v", err)
		}
	}
	c.Next()
}
